<script setup>
import { reactive, onMounted, watch } from 'vue';

const emits = defineEmits(['change']);
const Resd = reactive({
  code: '',
})
watch(() => Resd.code, (nv, ov) => {
  if (nv && nv !== ov) {
    drawPic();
  }
});
onMounted(() => {
  refresh();
  drawPic();
});
const drawPic = () => {
  const canvas = document.getElementById('piccode_canvans');
  const canvasWidth = canvas.offsetWidth, canvasHeight = canvas.offsetHeight;
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = randomColor(180, 240);
  ctx.strokeStyle = randomColor(180, 240);
  ctx.fillRect(0, 0, canvasWidth, canvasHeight);
  ctx.strokeRect(0, 0, canvasWidth, canvasHeight);
  for (let i = 0; i < Resd.code.length; i++) {
    for (let i = 0; i < 100; i++) {
      ctx.fillStyle = randomColor(0, 255);
      ctx.beginPath();
      ctx.arc(
        randomNum(0, canvasWidth),
        randomNum(0, canvasHeight),
        0.5,
        0,
        0.8 * Math.PI
      );
      ctx.fill();
    }
    ctx.fillStyle = randomColor(50, 160);
    ctx.font = randomNum(25, 30) + 'px SimHei';
    ctx.textBaseline = 'alphabetic';
    let x = (i + 1) * (canvasWidth / (Resd.code.length + 1));
    let y = randomNum(30, canvasHeight - 12);
    let deg = randomNum(-45, 45);
    ctx.translate(x, y);
    ctx.rotate((deg * Math.PI) / 180);
    ctx.fillText(Resd.code[i], 0, 0);
    ctx.rotate((-deg * Math.PI) / 180);
    ctx.translate(-x, -y);
  }
}
const refresh = () => {
  const words = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  // const words = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += words[Math.floor(Math.random() * 26)];
  }
  emits('change', code);
  Resd.code = code;
}
const randomColor = (min, max) => {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return 'rgb(' + r + ',' + g + ',' + b + ')';
}
const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
}
</script>

<template>
  <canvas id="piccode_canvans" @click="refresh()" />
</template>


<style lang="scss" scoped>
#piccode_canvans {
  width: 100%;
  height: 100%;
  cursor: pointer;
}
</style>